import requests
import json
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# 配置信息
APP_ID = "9R6E1S5QaNUOGY7YinLjjHDUV49ZkVmM"
SECRET_KEY = "hvZPgRzPcmS31ME4zqhKRzeDn5h3lKom"
URL = f"https://agentapi.baidu.com/assistant/getAnswer?appId={APP_ID}&secretKey={SECRET_KEY}"

# 请求头
headers = {"Content-Type": "application/json"}

# 用户输入
user_question = "有没有清淡食品推荐"

# 请求体
payload = {
    "message": {"content": {"type": "text", "value": {"showText": user_question}}},
    "source": APP_ID,
    "from": "openapi",
    "openId": "user_test_001",
}

# --- 增加重试机制 ---
session = requests.Session()
retry_strategy = Retry(
    total=3,  # 最大重试次数
    backoff_factor=1,  # 重试间隔时间（1秒，2秒，4秒...）
    status_forcelist=[429, 500, 502, 503, 504],  # 需要重试的状态码
    allowed_methods={"POST"},  # 仅对 POST 请求重试
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)

# 发送请求
try:
    print(f"向智能体发送请求: {user_question}")
    response = session.post(
        URL, headers=headers, data=json.dumps(payload), timeout=60  # 超时时间增加到 60 秒
    )
    response.raise_for_status()
    result = response.json()

    # 打印完整响应（调试用）
    print("\n完整响应:", json.dumps(result, indent=2, ensure_ascii=False))

    if result.get("status") == 0:
        data = result.get("data", {})
        thread_id = data.get("threadId")
        print(f"\n当前会话ID: {thread_id}")

        # 提取回答
        answers = data.get("content", [])
        for idx, ans in enumerate(answers):
            data_type = ans.get("dataType")
            content = ans.get("data", "")
            # 兼容不同 dataType
            if isinstance(content, dict):
                content = content.get("text", content)
            print(f"智能体回复 {idx+1} ({data_type}): {content}")

    else:
        print(f"请求失败: {result.get('status')} - {result.get('message')}")

except requests.exceptions.RequestException as e:
    print(f"网络请求异常: {e}")
except json.JSONDecodeError:
    print("解析响应失败，返回内容不是 JSON")
except Exception as e:
    print(f"其他错误: {e}")